package com.application.examples.controller;

import com.application.examples.entity.*;
import com.application.examples.utils.DateUtils;
import com.application.examples.utils.RestTemplateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * people对象的接口入口处
 * @author xiongwei_vendor
 * @date 2020/11/4 15:57
 */
@Slf4j
@RestController
@RequestMapping("/people")
@Api(value = "导出任务相关接口")
public class PeopleController {

    @PostMapping("/getPeople")
    @ApiOperation(value = "添加viper导出任务", httpMethod = "POST")
     public Response getPeople(){
        People people = new People();
        people.setName("法外狂徒张三");
        people.setAge(20);
        people.setBirthday(DateUtils.getNowDate());
        Response response = new Response();
        response.setCode(0);
        response.setData(people);
        response.setMessage("ok");
        return response;
     }

    @RequestMapping(value = "/getPeopleInfo", method = RequestMethod.GET)
    @ApiOperation(value = "Get Request 传递@RequestParam参数", notes = "仅传递@RequestParam 普通参数")
    @ApiImplicitParam(paramType = "query", name = "id", value = "人员ID", required = true, dataType = "Long")
    public BaseResponse getRequestParam(@RequestParam Long id) {
        return BaseResponse.success(CobraResultCodeConstant.SUCCESS);
    }

    @RequestMapping(value = "/getPathVariable/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "Get Request 传递@PathVariable参数", notes = "仅传递@PathVariable 路径参数")
    @ApiImplicitParam(name = "id", value = "测试id", dataType = "Integer", paramType = "path")
    public BaseResponse getPathVariable(@PathVariable(value = "id") Integer id) {
        log.info("getPathVariable param {}", id);
        return new BaseResponse(CobraResultCodeConstant.SUCCESS);
    }

    @RequestMapping(value = "/getRequired", method = RequestMethod.GET)
    @ApiOperation(value = "演示 @RequestParam 中 required 及 default ", notes = "注意defaultValue和required的结合使用")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "username", value = "用户名称", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "pageNum", value = "分页中的页数", dataType = "Integer"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "分页中每页的数据量", dataType = "Integer")
    })
    public BaseResponse getRequired(@RequestParam(value = "username") String username,
                                    @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                    @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        log.info("getRequired param {},{},{}", username, pageNum, pageSize);
        return new BaseResponse(CobraResultCodeConstant.SUCCESS);
    }

    @PostMapping(value = {"/postRequestBody"}, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "演示POST @RequestBody", notes = "注意引用的参数校验工具")
    @ApiImplicitParam(name = "accountRequestVO", value = "用户信息accountRequestVO", required = true, dataType = "AccountRequestVO")
    public BaseResponse postRequestBody(@RequestBody AccountRequestVO accountRequestVO, BindingResult bindingResult) {
        log.info("postRequestBody param {}", accountRequestVO);
        if (bindingResult.hasErrors()) {
            StringBuilder sb = new StringBuilder();
            bindingResult.getAllErrors().forEach(objectError ->
                    sb.append(objectError.getDefaultMessage())
            );
            return new BaseResponse("500", sb.toString());
        }
        return new BaseResponse(CobraResultCodeConstant.SUCCESS);
    }

    @DeleteMapping(value = {"/deleteByPathVariable/{type}/{id}"})
    @ApiOperation(value = "演示Delete @PathVariable", notes = "接收Delete request中PathVariable参数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "需要删除信息的type", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "id", value = "需要删除信息的id", required = true, dataType = "Integer", paramType = "path")
    })

    public BaseResponse deleteByPathVariable(@PathVariable(value = "id") Integer id, @PathVariable(value = "type") String type) {
        log.info("deleteByPathVariable param {} ,{}", id, type);
        return new BaseResponse(CobraResultCodeConstant.SUCCESS);
    }

    @PostMapping(value = "/upload/doc", headers = "content-type=multipart/form-data")
    @ApiOperation(value = "上传多文件并传递多种参数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accountId", value = "账号id", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "username", value = "账号名称", required = true, dataType = "String", paramType = "query")
    })

    public BaseResponse upload(@RequestParam("file") MultipartFile file, @RequestParam Integer accountId, @RequestParam String username) {
        log.info("upload file size {},accountId {},username {}", file.getName(), accountId, username);
        return new BaseResponse(CobraResultCodeConstant.SUCCESS);
    }

    @GetMapping(value = "/downloadFile")
    @ApiOperation(value = "下载文件")
    @ApiImplicitParam(name = "fileUrl", value = "远程文件地址", required = true, dataType = "String", paramType = "query")
    public BaseResponse download(HttpServletResponse response, @RequestParam String fileUrl) {
        log.info("download file url {}", fileUrl);
        try {
            String filename = StringUtils.getFilename(fileUrl);
            byte[] data = RestTemplateUtils.download(fileUrl);
            // ContentType 使用 multipart/form-data 能自动识别文件类型
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            OutputStream os = response.getOutputStream();
            if (null != data) {
                os.write(data);
            }
        } catch (Exception e) {
            log.error("download error", e);
        }
        return new BaseResponse(CobraResultCodeConstant.SUCCESS);
    }

}
